﻿using FluentValidation;
using Mes.Application.Common;
using Mes.Application.DTO.Inputs.Operations;
using Mes.Application.DTO.Inputs.WorkOrders;
using Mes.Application.DTO.Results.WorkOrders;
using Mes.Application.Services.WorkOrders;
using Mes.Application.Web.Controllers.MasterData;
using Mes.Domain.BoundedContext;
using Microsoft.AspNetCore.Mvc;

namespace Mes.Application.Web.Controllers.WorkOrders
{
    /// <summary>
    /// 工单控制器
    /// </summary>
    [ApiController]
    [Route("/api/v1")]
    public class WoController : ControllerBase
    {
        private readonly IWoService _woService;
        private readonly IValidator<AddWoInput> _addWoInputValidator;
        private readonly IValidator<GetWosInput> _getWosInputValidator;
        private readonly ILogger<WoController> _logger;

        /// <summary>
        /// 工单控制器
        /// </summary>
        /// <param name="woService"></param>
        /// <param name="addWoInputValidator"></param>
        /// <param name="getWosInputValidator"></param>
        /// <param name="logger"></param>
        public WoController(IWoService woService, IValidator<AddWoInput> addWoInputValidator, IValidator<GetWosInput> getWosInputValidator, ILogger<WoController> logger)
        {
            _woService = woService;
            _addWoInputValidator = addWoInputValidator;
            _getWosInputValidator = getWosInputValidator;
            _logger = logger;
        }

        /// <summary>
        /// 通过工艺新增工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("wo/process")]
        public async Task<ActionResult> AddWoByProcessAsync([FromBody] WoInputWithProcess input)
        {
            try
            {
                var result = await _addWoInputValidator.ValidateAsync(input);
                if (!result.IsValid)
                {
                    return BadRequest(result.Errors.First().ErrorMessage);
                }
                await _woService.AddWoByProcessAsync(input);
                return Ok();
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex.Message, ex);
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 新增工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("wo")]
        public async Task<ActionResult> AddWoAsync([FromBody] AddWoInput input)
        {
            try
            {
                var result = await _addWoInputValidator.ValidateAsync(input);
                if (!result.IsValid)
                {
                    return BadRequest(result.Errors.First().ErrorMessage);
                }
                await _woService.AddWoAsync(input);
                return Ok();
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex.Message, ex);
                return BadRequest(ex.Message);
            }
            
        }

        /// <summary>
        /// 编辑工单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPatch("wo")]
        public async Task<ActionResult> UpdateWoAsync([FromBody] UpdateWoInput input)
        {
            try
            {
                await _woService.UpdateWoAsync(input);
                return Ok();
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex.Message, ex);
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 删除工单
        /// </summary>
        /// <param name="wo_id"></param>
        /// <returns></returns>
        [HttpDelete("wo")]
        public async Task<ActionResult> DeleteWoesAsync(string wo_id)
        {
            try
            {
                await _woService.DeleteWoAsync(wo_id);
                return Ok();
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex.Message, ex);
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 查询工单分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("wos")]
        public async Task<ActionResult<PagedItemsData<WosResult>>> GetWoesAsync([FromQuery] GetWosInput input)
        {
            try
            {
                var result = await _getWosInputValidator.ValidateAsync(input);
                if (!result.IsValid)
                {
                    return BadRequest(result.Errors.First().ErrorMessage);
                }
                var wos = await _woService.GetWosAsync(input);
                return Ok(wos);
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex.Message, ex);
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 查询工单实体
        /// </summary>
        /// <param name="wo_id"></param>
        /// <returns></returns>
        [HttpGet("wo")]
        public async Task<ActionResult<WoResult>> GetWoAsync(string wo_id)
        {
            try
            {
                var response = await _woService.GetWoAsync(wo_id);
                return Ok(response);
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex.Message, ex);
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 查询所有工艺关联物料，以及物料BOM
        /// </summary>
        /// <returns></returns>
        [HttpGet("wo/processes")]
        public async Task<ActionResult<List<ProcessForWoResult>>> GetAllProcessesMaterialMaterialBOMAsync()
        {
            try
            {
                var response = await _woService.GetAllProcessesMaterialMaterialBOMAsync();
                return Ok(response);
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex.Message, ex);
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 移动作业顺序
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPatch("wo/job/route")]
        public async Task<ActionResult> MovingJobSequenceAsync(MovingJobSequenceInput input)
        {
            try
            {
                await _woService.MovingJobSequenceAsync(input);
                return Ok();
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex.Message, ex);
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 查询某个工单的路线信息，按顺序显示作业的操作编号
        /// </summary>
        /// <returns></returns>
        [HttpGet("wo/job/route")]
        public async Task<ActionResult<ItemsResult<WoJobRoutesResult>>> GetWoJobRoutesAsync(string wo_Id)
        {
            try
            {
                var response = await _woService.GetWoJobRoutesAsync(wo_Id);
                return Ok(response);
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex.Message, ex);
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 查询某道工艺关联的物料以及对应的物料清单
        /// </summary>
        /// <param name="processId"></param>
        /// <returns></returns>
        [HttpGet("wo/processmaterialbom")]
        public async Task<ActionResult<MaterialBOMResults>> GetProcessMaterialBOMAsync(string processId)
        {
            try
            {
                var response = await _woService.GetProcessMaterialBOMAsync(processId);
                return Ok(response);
            }
            catch (CustomException ex)
            {
                _logger.LogError(ex.Message, ex);
                return BadRequest(ex.Message);
            }
        }
    }
}
